package bb.lanxing.lib.devices.bici;

import bb.lanxing.lib.devices.bici.model.BiciFile;
import gov.nist.core.Separators;
import bb.lanxing.lib.devices.api.DeviceProvider;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.bici.cmd.FileTransCMD;
import bb.lanxing.lib.devices.bici.model.BiciDeviceInfo;
import bb.lanxing.lib.devices.core.utils.DeviceHelper;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class BiCiFileManager {
    public static final int BICI_FAILURE = 1;
    public static final String BICI_FILE_LIST = "filelist";
    public static final String BICI_INFO = "con";
    public static final int BICI_SUCCESS = 0;
    public static final String BODY_TAIL = ".l";
    public static final String HEAD_TAIL = ".h";
    private static BiCiFileManager INSTANCE = null;
    public static final int MAX_PROGRESS = 100;
    private static final int ONE_FILE_TITLE_LENGTH = 13;
    private final String BICI_TMP_FILE_SUFFIX = ".tmp";
    private File mBiCiFileRoot;
    private int mLastIndex;
    private int mTransResult;

    public static BiCiFileManager getInstance() {
        synchronized (BiCiFileManager.class) {
            if (INSTANCE == null) {
                INSTANCE = new BiCiFileManager();
            }
        }
        return INSTANCE;
    }

    private BiCiFileManager() {
        DeviceProvider deviceProvider = DeviceHelper.getDeviceProvider();
        if (deviceProvider == null) {
            return;
        }
        List<SmartDevice> devicesByType = deviceProvider.getDevicesByType(1);
        SmartDevice smartDevice = (devicesByType == null || devicesByType.isEmpty()) ? null : devicesByType.get(0);
        if (smartDevice == null) {
            return;
        }
        File file = new File(DeviceHelper.getWorkDir(1), smartDevice.getAddress().replaceAll(Separators.COLON, ""));
        this.mBiCiFileRoot = file;
        if (file.exists()) {
            return;
        }
        this.mBiCiFileRoot.mkdirs();
    }

    private boolean prepareTransfer(String str) {
        if (this.mBiCiFileRoot == null) {
            return false;
        }
        File generateTmpFile = generateTmpFile(str);
        return !generateTmpFile.exists() || generateTmpFile.delete();
    }

    public synchronized void update(FileTransCMD fileTransCMD, BiciNotifier biciNotifier) throws IOException {
        String transName = fileTransCMD.getTransName();
        File file = this.mBiCiFileRoot;
        if (file != null && file.exists() && transName != null) {
            File generateTmpFile = generateTmpFile(fileTransCMD.getTransName());
            boolean z = fileTransCMD.getIndex() + 1 == fileTransCMD.getPackageCount();
            if (fileTransCMD.getIndex() == 0) {
                this.mTransResult = 0;
                this.mLastIndex = 0;
                prepareTransfer(fileTransCMD.getTransName());
                if (!generateTmpFile.createNewFile()) {
                    biciNotifier.notifyCmdStatus(fileTransCMD.getCommandId(), 1);
                    this.mTransResult = 1;
                }
            } else if (this.mTransResult == 1) {
                return;
            } else {
                boolean endsWith = transName.toLowerCase().endsWith(".l");
                if (!generateTmpFile.exists()) {
                    biciNotifier.notifyCmdStatus(fileTransCMD.getCommandId(), 1);
                    this.mTransResult = 1;
                    return;
                } else if (!endsWith && fileTransCMD.getIndex() - 1 != this.mLastIndex) {
                    biciNotifier.notifyCmdStatus(fileTransCMD.getCommandId(), 1);
                    this.mTransResult = 1;
                    return;
                }
            }
            float index = (fileTransCMD.getIndex() + 1) / fileTransCMD.getPackageCount();
            this.mLastIndex = fileTransCMD.getIndex();
            FileOutputStream fileOutputStream = new FileOutputStream(generateTmpFile, true);
            fileOutputStream.write(fileTransCMD.getContent());
            fileOutputStream.close();
            if (!transName.toLowerCase().endsWith(".h")) {
                biciNotifier.notifyProgressUpdate(fileTransCMD.getCommandId(), Math.min(100, (int) (index * 100.0f)));
            }
            if (z) {
                File file2 = new File(this.mBiCiFileRoot, parseFileName(generateTmpFile.getAbsolutePath()));
                if (!file2.exists() || file2.delete()) {
                    generateTmpFile.renameTo(file2);
                }
                biciNotifier.notifyGetFile(file2.getAbsolutePath());
                generateTmpFile.delete();
            }
        }
    }

    public BiciDeviceInfo getBiCiInfo() {
        File file = this.mBiCiFileRoot;
        if (file == null || !file.exists()) {
            return null;
        }
        File file2 = new File(this.mBiCiFileRoot, "con");
        if (!file2.exists()) {
            return null;
        }
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            FileInputStream fileInputStream = new FileInputStream(file2);
            byte[] bArr = new byte[1024];
            while (true) {
                int read = fileInputStream.read(bArr);
                if (read != -1) {
                    byteArrayOutputStream.write(bArr, 0, read);
                } else {
                    fileInputStream.close();
                    byteArrayOutputStream.close();
                    return new BiciDeviceInfo(byteArrayOutputStream.toByteArray());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void clear() {
        File[] listFiles;
        File file = this.mBiCiFileRoot;
        if (file == null || (listFiles = file.listFiles()) == null) {
            return;
        }
        for (File file2 : listFiles) {
            file2.delete();
        }
    }

    public List<BiciFile> getBiCiFiles() {
        File file = this.mBiCiFileRoot;
        ArrayList arrayList = null;
        if (file != null && file.exists()) {
            File file2 = new File(this.mBiCiFileRoot, "filelist");
            if (!file2.exists()) {
                return null;
            }
            arrayList = new ArrayList();
            try {
                FileInputStream fileInputStream = new FileInputStream(file2);
                byte[] bArr = new byte[13];
                while (fileInputStream.read(bArr) != -1) {
                    arrayList.add(new BiciFile(bArr));
                }
                fileInputStream.close();
            } catch (Exception e) {
                arrayList.clear();
                e.printStackTrace();
            }
        }
        return arrayList;
    }

    public List<BiciFile> getSyncFiles() {
        List<BiciFile> biCiFiles = getBiCiFiles();
        if (biCiFiles != null) {
            ListIterator<BiciFile> listIterator = biCiFiles.listIterator();
            while (listIterator.hasNext()) {
                if (listIterator.next().getType() != 76) {
                    listIterator.remove();
                }
            }
        }
        return biCiFiles;
    }

    public boolean deleteFileList() {
        if (this.mBiCiFileRoot != null) {
            File file = new File(this.mBiCiFileRoot, "filelist");
            if (!file.exists()) {
                return false;
            }
            return file.delete();
        }
        return false;
    }

    public boolean deleteBiciInfo() {
        if (this.mBiCiFileRoot != null) {
            File file = new File(this.mBiCiFileRoot, "con");
            if (!file.exists()) {
                return false;
            }
            return file.delete();
        }
        return false;
    }

    public List<File> getBiciFiles() {
        File[] listFiles;
        File file = this.mBiCiFileRoot;
        ArrayList arrayList = null;
        if (file != null && file.exists() && (listFiles = this.mBiCiFileRoot.listFiles()) != null && listFiles.length != 0) {
            arrayList = new ArrayList();
            for (File file2 : listFiles) {
                if (!file2.getAbsolutePath().endsWith(".tmp")) {
                    arrayList.add(file2);
                }
            }
        }
        return arrayList;
    }

    private File generateTmpFile(String str) {
        return new File(this.mBiCiFileRoot, str + ".tmp");
    }

    private String parseFileName(String str) {
        String name = new File(str).getName();
        int lastIndexOf = name.lastIndexOf(".");
        if (lastIndexOf == -1) {
            lastIndexOf = name.length();
        }
        return name.substring(0, lastIndexOf);
    }
}
